//
//  XUIFoldList.m
//  etionUI
//
//  Created by wjxfhxy on 15/12/21.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "XUIFoldList.h"

@class XUIFoldListScrollHeadView;

@interface FoldStatus : NSObject

@property(nonatomic,retain) XUIFoldListHeaderView *headerView;
@property(nonatomic,assign) BOOL fold; //NO，折叠

@end

@implementation FoldStatus

-(void)dealloc
{
    [_headerView release_mm];
    superdealloc_mm;
}

@end

@implementation XUIFoldListCell

@end

@protocol XUIFoldListHeaderViewDelegate <NSObject>

-(void)didSelectedFoldListHeaderView:(XUIFoldListHeaderView*)foldListHeaderView;

-(void)didClickededDeleteButtonOfFoldListHeaderView:(XUIFoldListHeaderView*)foldListHeaderView;

-(void)foldListHeaderView:(XUIFoldListHeaderView*)foldListHeaderView didHiddenDeleteButton:(BOOL)hidden;

-(BOOL)willDisplayDeleteButtonOfFoldListHeaderView:(XUIFoldListHeaderView*)foldListHeaderView;

@end

@interface XUIFoldListHeaderView()<UIScrollViewDelegate,XUIButtonDelegate>
{
    UIScrollView *_scrollView;
    UIView *_headSectionContainView;
    XUIButton *_deleteBtn;
    BOOL _hiddenDeleteLabel;
    
    UIView *_headLineView;
    
    BOOL _hiddenDeleteBtn;
}

@property(nonatomic,assign) id<XUIFoldListHeaderViewDelegate> delegate;

@end

@implementation XUIFoldListHeaderView

@synthesize delegate = _delegate;
@synthesize contentView = _headSectionContainView;

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithReuseIdentifier:reuseIdentifier];
    
    UITapGestureRecognizer *tap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headSectionTapGestureRecognizer:)] autorelease_mm];
    [super.contentView addGestureRecognizer:tap];
    
    _deleteBtn = [[XUIButton buttonWithStyleType:XUIButtonStyleTypeCustom delegate:self] retain_mm];
    _deleteBtn.frame = CGRectMake(0, 0, 65, self.height);
    _deleteBtn.backgroundColor = [UIColor redColor];
    [_deleteBtn SetTitleColor:[UIColor whiteColor]];
    [_deleteBtn SetTitle:@"删除"];
    [super.contentView addSubview:_deleteBtn];
    
    _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    _scrollView.delegate = self;
    _scrollView.backgroundColor = [UIColor clearColor];
    _scrollView.showsHorizontalScrollIndicator = NO;
    [super.contentView addSubview:_scrollView];
    
    _headSectionContainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    _headSectionContainView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_headSectionContainView];
    
    _headLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.5)];
    _headLineView.backgroundColor = [UITableView appearance].separatorColor;
    [_headSectionContainView addSubview:_headLineView];
    
    _hiddenDeleteLabel = YES;
    
    return self;
}

-(void)dealloc
{
    [_headLineView release_mm];
    [_deleteBtn release_mm];
    [_scrollView release_mm];
    [_headSectionContainView release_mm];
    superdealloc_mm;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    _scrollView.frame = self.bounds;
    
    _scrollView.contentSize = CGSizeMake(self.width + _deleteBtn.width, 0);
    
    _headSectionContainView.frame = _scrollView.bounds;
    
    _deleteBtn.frame = CGRectMake(self.width - _deleteBtn.width, 0, _deleteBtn.width, self.height);
    
    _headLineView.frame = CGRectMake(0, self.height - 0.5, self.width, 0.5);
}

-(void)headSectionTapGestureRecognizer:(UITapGestureRecognizer*)gestureRecognozer
{
    if(gestureRecognozer.state == UIGestureRecognizerStateEnded)
    {
        if(_scrollView.userInteractionEnabled == YES)
        {
            [_delegate didSelectedFoldListHeaderView:self];
        }
        else
        {
            _scrollView.width += _deleteBtn.width;
            [_scrollView setContentOffset:CGPointZero animated:YES];
            _scrollView.userInteractionEnabled = YES;
            
            [_delegate foldListHeaderView:self didHiddenDeleteButton:YES];
        }
    }
}

//-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
//{
//    BOOL b = [_delegate willDisplayDeleteButtonOfFoldListHeaderView:self];
//    if(b == NO)
//    {
//        scrollView.scrollEnabled = NO;
//        [scrollView setContentOffset:CGPointZero animated:NO];
//    //    scrollView.scrollEnabled = YES;
//    }
//}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    BOOL b = [_delegate willDisplayDeleteButtonOfFoldListHeaderView:self];
    if(b == NO)
    {
        scrollView.contentOffset = CGPointZero;
        
        return;
    }
    
    if(scrollView.contentOffset.x < 0)
    {
        scrollView.contentOffset = CGPointZero;
    }
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(ABS(scrollView.contentOffset.x) < _deleteBtn.width)
    {
        [scrollView setContentOffset:CGPointZero animated:YES];
    }
    else if(scrollView.contentOffset.x >= _deleteBtn.width)
    {
        scrollView.userInteractionEnabled = NO;
        
        [_delegate foldListHeaderView:self didHiddenDeleteButton:NO];
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(_hiddenDeleteBtn == NO && scrollView.contentOffset.x >= _deleteBtn.width)
    {
        scrollView.width -= _deleteBtn.width;
        
//        scrollView.userInteractionEnabled = NO;
//        
//        [_delegate foldListHeaderView:self didHiddenDeleteButton:NO];
    }
}

-(void)hiddenDeleteButton
{
    _hiddenDeleteBtn = YES;
    
    if(_scrollView.decelerating  == NO)
        _scrollView.width += _deleteBtn.width;
    
    [_scrollView setContentOffset:CGPointZero animated:YES];
    _scrollView.userInteractionEnabled = YES;
    
    _hiddenDeleteBtn = NO;
}

-(void)clickedUpInsideOfButton:(XUIButton *)btn
{
    [_delegate didClickededDeleteButtonOfFoldListHeaderView:self];
}


//-(void)shadePointInDeleteLabel
//{
//    [_delegate didClickededDeleteButtonOfFoldListScrollHeadSection:self];
//}
//
//-(void)shadePointInScrollView
//{
//    _scrollView.width += _deleteLabel.width;
//    [_scrollView setContentOffset:CGPointZero animated:YES];
//    _hiddenDeleteLabel = YES;
//
//}
//
//-(void)clickedShadeAtPoint:(CGPoint)clickPoint
//{
//    CGPoint point = [self.superview convertPoint:clickPoint toView:self];
//    if(CGRectContainsPoint(_deleteLabel.frame, point))
//    {
//        [self shadePointInDeleteLabel];
//    }
//    else
//    {
//        [self shadePointInScrollView];
//    }
//}

@end

@interface XUIFoldListDeleteShadeView : UIView
{
    void(^_clickedBlock)();
}
@end

@implementation XUIFoldListDeleteShadeView

-(id)initWithFrame:(CGRect)frame block:(void(^)())block
{
    self = [super initWithFrame:frame];
    
    _clickedBlock = Block_copy(block);
    
    return self;
}

-(void)dealloc
{
    Block_release(_clickedBlock);
    superdealloc_mm;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    _clickedBlock();
}

@end

@interface XUIFoldList ()<XUITableViewDelegate,UITableViewDataSource,XUIFoldListHeaderViewDelegate>
{
    XUITableView *_tableView;
    
    NSMutableDictionary *_foldDic;
}

@end

@implementation XUIFoldList

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    self.backgroundColor = [UIColor whiteColor];
    
    _tableView = [[XUITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self addSubview:_tableView];
    
    if (@available(iOS 11.0, *))
    {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
        CGFloat top = _tableView.contentInset.top + [XUINavigationController navigationController].navigationBar.bottom;
        CGFloat left = _tableView.contentInset.left;
        CGFloat bottom = _tableView.contentInset.bottom;
        CGFloat right = _tableView.contentInset.right;
        _tableView.contentInset = UIEdgeInsetsMake(top,left,bottom,right);
        _tableView.scrollIndicatorInsets = UIEdgeInsetsMake(top,left,bottom,right);
    }
    
    _oneSectionUnfold = YES;
    
    return self;
}

-(void)dealloc
{
    [_foldDic release_mm];
    [_tableView release_mm];
    superdealloc_mm;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    _tableView.frame = self.bounds;
}

-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    _tableView.frame = self.bounds;
}

-(void)didAddSubview:(UIView *)subview
{
    UIViewController *viewController = [UIViewController superViewController:subview];
    if( viewController != nil)
    {
        if(viewController.automaticallyAdjustsScrollViewInsets == YES)
            _tableView.contentInset = UIEdgeInsetsMake(49, 0, 0, 0);
    }
    
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
#ifdef __IPHONE_8_0
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
#endif
}

-(void)setSeparatorExistFollowCell:(BOOL)separatorExistFollowCell
{
    _tableView.separatorExistFollowCell =  separatorExistFollowCell;
}

- (void)reloadData
{
    ReleaseObj(_foldDic);
    [_tableView reloadData];
}

-(void)registerClass:(Class)aClass forHeaderViewReuseIdentifier:(NSString *)identifier
{
    [_tableView registerClass:aClass forHeaderFooterViewReuseIdentifier:identifier];
}

- (void)scrollCell:(XUIFoldListCell*)cell rectToVisible:(CGRect)rect animated:(BOOL)animated
{
    rect = [_tableView convertRect:rect fromView:cell];
    [_tableView scrollRectToVisible:rect animated:animated];
}

-(XUIFoldListHeaderView*)dequeueReusableHeaderViewWithIdentifier:(NSString *)identifier
{
    return (XUIFoldListHeaderView*)[_tableView dequeueReusableHeaderFooterViewWithIdentifier:identifier];
}

- (XUIFoldListHeaderView *)headerViewForSection:(NSUInteger)section
{
    return (XUIFoldListHeaderView *)[_tableView headerViewForSection:section];
}

- (XUIFoldListCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (XUIFoldListCell*)[_tableView cellForRowAtIndexPath:indexPath];
}

- (NSIndexPath *)indexPathForCell:(XUIFoldListCell*)cell
{
    return [_tableView indexPathForCell:cell];
}

- (NSArray*)currentHeadViewSectionForFoldStatus:(BOOL)fold
{
    NSMutableArray *sections = [NSMutableArray new];
    [_foldDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
    {
        FoldStatus *s = obj;
        if(s.fold == fold)
        {
            [sections addObject:key];
        }
    }];
    return sections;
}

-(void)setFoldStatus:(BOOL)fold forSection:(NSUInteger)section
{
    ((FoldStatus*)_foldDic[@(section)]).fold = fold;
}

-(BOOL)foldStatusForSection:(NSUInteger)section
{
    return ((FoldStatus*)_foldDic[@(section)]).fold;
}

-(XUIFoldListHeaderView*)sectionViewForSection:(NSUInteger)section
{
    return ((FoldStatus*)_foldDic[@(section)]).headerView;
}

-(NSUInteger)sectionForHeaderView:(XUIFoldListHeaderView*)headerView
{
    __block NSUInteger i = NSNotFound;
    [_foldDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
    {
        FoldStatus *s = obj;
        if(s.headerView == headerView)
        {
            i = [key unsignedIntegerValue];
            *stop = YES;
        }
    }];
    return i;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger sections = [_dataSource numberOfSectionsInFoldList:self];
    
    if(_foldDic == nil)
    {
        _foldDic = [NSMutableDictionary new];
        //折起来
        for(NSInteger i =0;i < sections;i++)
        {
            FoldStatus *status = [FoldStatus new];
            status.fold = YES;
            status.headerView = nil;
            _foldDic[@(i)] = status;
        }
    }
    
    return sections;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    BOOL fold = [self foldStatusForSection:section];
    //折起来
    if(fold == YES)
        return 0;
    return [_dataSource foldList:self numberOfRowsInSection:section];
}

-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return [_delegate foldList:self heightForRowAtIndexPath:indexPath];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return [_delegate foldList:self heightForHeaderInSection:section];
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    XUIFoldListHeaderView *headerView = [_dataSource foldList:self headerViewforHeaderInSection:section];
    
    headerView.delegate = self;
    
    [_foldDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
    {
        FoldStatus *s = obj;
        if(s.headerView == headerView)
        {
            s.headerView = nil;
            *stop = YES;
        }
    }];
    
    ((FoldStatus*)_foldDic[@(section)]).headerView = headerView;
    
    return headerView;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XUIFoldListCell *cell = [_dataSource foldList:self cellforRowAtIndexPath:indexPath];
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        UIEdgeInsets edge = UIEdgeInsetsZero;
//        if([_ctable.delegate respondsToSelector:@selector(tableView:setSeparatorInsetForRowAtIndexPath:)])
//            edge = [_ctable.delegate tableView:_ctable setSeparatorInsetForRowAtIndexPath:indexPath];
        [cell setSeparatorInset:edge];
    }
    
#ifdef __IPHONE_8_0
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
#endif
}

-(BOOL)willDisplayDeleteButtonOfFoldListHeaderView:(XUIFoldListHeaderView*)foldListHeaderView
{
    if([_delegate respondsToSelector:@selector(foldList:willDisplayDeleteButtonInSection:)])
        return [_delegate foldList:self willDisplayDeleteButtonInSection:[self sectionForHeaderView:foldListHeaderView]];
    return YES;
}

-(void)foldListHeaderView:(XUIFoldListHeaderView *)foldListHeaderView didHiddenDeleteButton:(BOOL)hidden
{
    if(hidden == NO)
    {
        __block XUIFoldListDeleteShadeView *shadeA;
        __block XUIFoldListDeleteShadeView *shadeB;
        
        shadeA = [[[XUIFoldListDeleteShadeView alloc] initWithFrame:CGRectMake(0, 0, _tableView.width, foldListHeaderView.top) block:^(CGPoint clickPoint)
        {
            [foldListHeaderView hiddenDeleteButton];
            [shadeA removeFromSuperview];
            [shadeB removeFromSuperview];
        }] autorelease_mm];
        shadeA.tag = 100000;
        [_tableView addSubview:shadeA];
        
        shadeB = [[[XUIFoldListDeleteShadeView alloc] initWithFrame:CGRectMake(0, foldListHeaderView.bottom, _tableView.width, _tableView.height - foldListHeaderView.bottom) block:^(CGPoint clickPoint)
        {
            [foldListHeaderView hiddenDeleteButton];
            [shadeA removeFromSuperview];
            [shadeB removeFromSuperview];
        }] autorelease_mm];
        shadeB.tag = 200000;
        [_tableView addSubview:shadeB];
    }
    else
    {
        XUIFoldListDeleteShadeView *shadeA = (XUIFoldListDeleteShadeView *)[_tableView viewWithTag:100000];
        [shadeA removeFromSuperview];
        XUIFoldListDeleteShadeView *shadeB = (XUIFoldListDeleteShadeView *)[_tableView viewWithTag:200000];
        [shadeB removeFromSuperview];
    }
}

-(void)didClickededDeleteButtonOfFoldListHeaderView:(XUIFoldListHeaderView *)foldListHeaderView
{
    NSInteger clickedSection = [self sectionForHeaderView:foldListHeaderView];
    
    XUIFoldListDeleteShadeView *shadeA = (XUIFoldListDeleteShadeView *)[_tableView viewWithTag:100000];
    [shadeA removeFromSuperview];
    XUIFoldListDeleteShadeView *shadeB = (XUIFoldListDeleteShadeView *)[_tableView viewWithTag:200000];
    [shadeB removeFromSuperview];
    
    if([_delegate respondsToSelector:@selector(foldList:deleteHeaderInSection:)])
    {
        BOOL b = [_delegate foldList:self deleteHeaderInSection:clickedSection];
        
        if(b == YES)
        {
            NSArray *allKey = [_foldDic allKeys];
            for(NSInteger i = clickedSection + 1; i < allKey.count ;i++)
            {
                _foldDic[@(i - 1)] = _foldDic[@(i)];
            }
            
            [_foldDic removeObjectForKey:@(allKey.count - 1)];
            
            [_tableView deleteSections:[NSIndexSet indexSetWithIndex:clickedSection] withRowAnimation:UITableViewRowAnimationFade];
        }
    }
}

-(void)didSelectedFoldListHeaderView:(XUIFoldListHeaderView *)foldListHeaderView
{
    NSInteger clickedSection = [self sectionForHeaderView:foldListHeaderView];
    
    if(_oneSectionUnfold == YES)
    {
        __block NSInteger section = 0;
        __block BOOL fold = YES;
        [_foldDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
        {
            FoldStatus *s = obj;
            BOOL f = s.fold;
            //展开了
            if(f == NO)
            {
                section = [key integerValue];
                fold = f;
                *stop = YES;
            }
        }];
        
        //没有展开的
        if(fold == YES)
        {
            if([_delegate respondsToSelector:@selector(foldList:willClickedHeaderInSection:preClickedHeaderInSection:)])
            {
                if([_delegate foldList:self willClickedHeaderInSection:clickedSection preClickedHeaderInSection:NSNotFound] == NO)
                    return;
            }
            
            //展开了
            [self setFoldStatus:NO forSection:clickedSection];
            [_tableView reloadSections:[NSIndexSet indexSetWithIndex:clickedSection] withRowAnimation:UITableViewRowAnimationFade];
            
            if([_delegate respondsToSelector:@selector(foldList:didClickedHeaderInSection:preClickedHeaderInSection:)])
                [_delegate foldList:self didClickedHeaderInSection:clickedSection preClickedHeaderInSection:NSNotFound];
        }
        else
        {
            if(clickedSection == section)
            {
                if([_delegate respondsToSelector:@selector(foldList:willClickedHeaderInSection:preClickedHeaderInSection:)])
                {
                    if([_delegate foldList:self willClickedHeaderInSection:clickedSection preClickedHeaderInSection:clickedSection] == NO)
                        return;
                }
                
                [self setFoldStatus:YES forSection:clickedSection];
                [_tableView reloadSections:[NSIndexSet indexSetWithIndex:clickedSection] withRowAnimation:UITableViewRowAnimationFade];
                
                if([_delegate respondsToSelector:@selector(foldList:didClickedHeaderInSection:preClickedHeaderInSection:)])
                    [_delegate foldList:self didClickedHeaderInSection:clickedSection preClickedHeaderInSection:clickedSection];
            }
            else
            {
                if([_delegate respondsToSelector:@selector(foldList:willClickedHeaderInSection:preClickedHeaderInSection:)])
                {
                    if([_delegate foldList:self willClickedHeaderInSection:clickedSection preClickedHeaderInSection:section] == NO)
                        return;
                }
                
                [self setFoldStatus:NO forSection:clickedSection];
                [self setFoldStatus:YES forSection:section];
                
                [_tableView beginUpdates];
                [_tableView reloadSections:[NSIndexSet indexSetWithIndex:clickedSection] withRowAnimation:UITableViewRowAnimationFade];
                [_tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
                [_tableView endUpdates];
                
                if([_delegate respondsToSelector:@selector(foldList:didClickedHeaderInSection:preClickedHeaderInSection:)])
                    [_delegate foldList:self didClickedHeaderInSection:clickedSection preClickedHeaderInSection:section];
            }
        }
    }
}

- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(XUIFoldListRowAnimation)animation
{
    [_tableView reloadSections:sections withRowAnimation:animation];
}

- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(XUIFoldListRowAnimation)animation
{
    for(NSInteger i = sections.firstIndex;i <= sections.lastIndex;i++)
    {
        FoldStatus *status = [FoldStatus new];
        status.fold = YES;
        status.headerView = nil;
        _foldDic[@(i)] = status;
    }
    
    [_tableView insertSections:sections withRowAnimation:animation];
}

@end
